﻿using EM.FrameWork.Paging;
using EM.OA.BLL;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EM.OA.Portal.Controllers
{
    public class WFFlowConfigController : BaseAuthController
    {
        /// <summary>
        /// 返回Index视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public JsonResult GetList(string page, string rows)
        {
            WFFlowConfigBLL bll = new WFFlowConfigBLL();

            List<EMOA_WF_FlowConfig> celist = new List<EMOA_WF_FlowConfig>();
            string _flowKind = GetParam("j_flowKind");
            string _configName = GetParam("j_configName");

            EMOA_WF_FlowConfig model = new EMOA_WF_FlowConfig();

            if (!string.IsNullOrEmpty(_flowKind))
                model.FlowKind = new Guid(_flowKind);
            model.FlowConfigName = _configName;

            PagedList<EMOA_WF_FlowConfig> list = bll.GetConfigList(model, new PageEntity() { PageIndex = Convert.ToInt32(page), PageSize = Convert.ToInt32(rows) });

            List<object> result = new List<object>();
            
            list.ForEach(p =>
            {
                result.Add(new WFFlowConfigModels().ToModel(p));
            });

            return ToJson(result, list.TotalItemCount);
        }

        /// <summary>
        /// 根据流程ID和步骤级别查找审核人(初次提交时)
        /// </summary>
        /// <returns></returns>
        public ActionResult GetApprovalUsers()
        {
            string _flowConfigID = Request.QueryString["flowConfigID"].ToString();
            string _stepLevel = Request.QueryString["stepLevel"].ToString();
            
            EMOA_WF_FlowConfigDetail modelDetail = new EMOA_WF_FlowConfigDetail();

            WFFlowConfigDetailBLL bllDetail = new WFFlowConfigDetailBLL();
            modelDetail = bllDetail.GetList(p => p.FlowConfigID == Guid.Parse(_flowConfigID) && p.StepLevel == int.Parse(_stepLevel)).FirstOrDefault();

            string userName = string.Empty;
            userName = new UserBLL().GetEntity(modelDetail.ApprovalUserID.Value).EmployeeName;

            string resultStr = "";
            resultStr += "[";
            resultStr += "{";
            resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"selected\": \"true  \"", modelDetail.ApprovalUserID.Value.ToString(), userName);
            resultStr += "},";
            //foreach (EMOA_Dictionary item in list)
            //{
            //    resultStr += "{";
            //    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\"", item.DictionaryID.ToString(), item.DictionaryName);
            //    resultStr += "},";
            //}
            resultStr = resultStr.Substring(0, resultStr.Length - 1);
            resultStr += "]";
            return Content(resultStr);
        }

        /// <summary>
        /// 第二次绑定审批人
        /// </summary>
        /// <returns></returns>
        public ActionResult GetApprovalUsersList()
        {
            //需优化成存储过程返回下一个userlist
            //string _flowConfigID = Request.QueryString["flowConfigID"].ToString();
            string _applyID = Request.QueryString["applyID"].ToString();

            EMOA_WF_Approval approval = new EMOA_WF_Approval();
            WFApprovalBLL wfApprovalbll = new WFApprovalBLL();
            approval = wfApprovalbll.GetList(p=>p.ApplyID == Guid.Parse(_applyID),q=>q.CreateTime,true).FirstOrDefault();
            string resultStr = "";
            if (approval.FlowConfigDetailID != new Guid())
            {
                //根据applyid找flowConfigID
                Guid flowConfigID = new WFApplyBLL().GetEntity(approval.ApplyID).ApplyFlowConfigID;
                //根据flowConfigDetailID找它的stemLevel
                int _stepLevel = new WFFlowConfigDetailBLL().GetEntity(approval.FlowConfigDetailID).StepLevel.Value;
                //根据stepLevel和flowConfigID找到他的下一级别EMOA_WF_FlowConfigDetail申请人
                EMOA_WF_FlowConfigDetail modelDetail = new EMOA_WF_FlowConfigDetail();
                modelDetail = new WFFlowConfigDetailBLL().GetList(p => p.FlowConfigID == flowConfigID && p.StepLevel > _stepLevel).FirstOrDefault();

                if (modelDetail!=null &&(modelDetail.ApprovalUserID.HasValue || modelDetail.ApprovalRoleID.HasValue))
                {
                    //暂时没考虑角色
                    string userName = string.Empty;
                    userName = new UserBLL().GetEntity(modelDetail.ApprovalUserID.Value).EmployeeName;

                    resultStr += "[";
                    resultStr += "{";
                    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"selected\": \"true  \"", modelDetail.ApprovalUserID.Value.ToString(), userName);
                    resultStr += "},";
                    //foreach (EMOA_Dictionary item in list)
                    //{
                    //    resultStr += "{";
                    //    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\"", item.DictionaryID.ToString(), item.DictionaryName);
                    //    resultStr += "},";
                    //}
                    resultStr = resultStr.Substring(0, resultStr.Length - 1);
                    resultStr += "]";
                }
                else
                {
                    resultStr += "[";
                    resultStr += "{";
                    resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"selected\": \"true  \"", new Guid().ToString(), "");
                    resultStr += "}";
                    resultStr += "]";
                }
            }

            return Content(resultStr);
        }

        /// <summary>
        /// 获取工作流步骤明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult GetListDetail()
        {

            string _flowConfigID = GetParam("j_flowConfigID");
            List<object> list = new List<object>();
            List<EMOA_WF_FlowConfigDetail> listDetail = new List<EMOA_WF_FlowConfigDetail>();
            if (!string.IsNullOrEmpty(_flowConfigID))
            {
                
                WFFlowConfigDetailBLL bllDetail = new WFFlowConfigDetailBLL();
                listDetail = bllDetail.GetList(p => p.FlowConfigID == Guid.Parse(_flowConfigID),q=>q.StepLevel);
                listDetail.ForEach(p => {
                    list.Add(new WFFlowConfigDetailModels().ToModel(p));
                });
            }

            return ToJson(list, listDetail.Count);
        }
        
       /// <summary>
        /// 工作流步骤明细
       /// </summary>
       /// <param name="model"></param>
        public ActionResult AddDetail(WFFlowConfigModels model)
        {
            EMOA_WF_FlowConfigDetail modelDetail = new EMOA_WF_FlowConfigDetail();
            modelDetail.FlowConfigDetailID = Guid.NewGuid();
            modelDetail.FlowConfigID = model.FlowConfigID;
            List<EMOA_WF_FlowConfigDetail> listDetail = new List<EMOA_WF_FlowConfigDetail>();
            WFFlowConfigDetailBLL bllDetail = new WFFlowConfigDetailBLL();
            listDetail = bllDetail.GetList(p => p.FlowConfigID == model.FlowConfigID);
            if (listDetail.Count > 0)
                modelDetail.StepLevel = listDetail.OrderByDescending(p => p.StepLevel).ToList().FirstOrDefault().StepLevel + 1;
            else
                modelDetail.StepLevel = 1;
            modelDetail.StepName = model.StepName;
            modelDetail.ApprovalUserID = model.ApprovalUserID;
            modelDetail.ApprovalRoleID = model.ApprovalRoleID;
            //ListConfigDetail.Add(modelDetail);

            WFFlowConfigDetailBLL bll = new WFFlowConfigDetailBLL();

            if (bll.Add(modelDetail))
            {
                return Content("OK");
            }
            else
            {
                return Content("增加失败");
            }

        }

        /// <summary>
        /// 增加实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(WFFlowConfigModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WFFlowConfigBLL bll = new WFFlowConfigBLL();
                    EMOA_WF_FlowConfig entity = model.ToEntity<EMOA_WF_FlowConfig>();
                    entity.FlowConfigID = Guid.NewGuid();
                    entity.CreateBy = CurrentUser.UserID;
                    entity.CreateTime = DateTime.Now;
                    if (bll.Add(entity))
                    {
                        return Content("OK");
                    }
                    else
                    {
                        return Content("增加失败");
                    }
                }
                else
                    return Content("验证失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(WFFlowConfigModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WFFlowConfigBLL bll = new WFFlowConfigBLL();
                    EMOA_WF_FlowConfig entity = bll.GetEntity(model.FlowConfigID);
                    entity = model.ToEntity<EMOA_WF_FlowConfig>(entity);
                    entity.UpdateBy = CurrentUser.UserID;
                    entity.UpdateTime = DateTime.Now;
                    if (bll.Update(entity))
                        return Content("OK");
                    else
                        return Content("修改失败");
                }
                else
                {
                    return Content("验证失败");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string id)
        {
            try
            {
                WFFlowConfigBLL bll = new WFFlowConfigBLL();
                if (bll.Delete(Guid.Parse(id)))
                    return Content("OK");
                else
                    return Content("删除失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

    }
}